//
//  GDPageController.m
//  美团试验 (自己)
//
//  Created by 热带雨林 on 17/2/15.
//  Copyright © 2017年 热带雨林. All rights reserved.
//

#import "GDPageController.h"
#import "GDDetailsViewController.h"
#import "CZAdditions.h"
#import "GDBuyCarLL.h"
#import "Masonry.h"

@interface GDPageController ()<UIPageViewControllerDataSource,UIPageViewControllerDelegate,CAAnimationDelegate>

@property(nonatomic)BOOL isEND;

@property(nonatomic, weak)GDBuyCarLL *buyCarLL;

@end

@implementation GDPageController

- (void)viewDidLoad {
    [super viewDidLoad];
        
    //创建翻页控制器
    //如果有过多的子控制器的界面，就会直接使用PageController
    UIPageViewController *pageVC = [[UIPageViewController alloc]initWithTransitionStyle:UIPageViewControllerTransitionStyleScroll navigationOrientation:UIPageViewControllerNavigationOrientationHorizontal options:nil];
    
//    GDDetailsViewController *detailsVC = [[GDDetailsViewController alloc]init];
//    
//    
//    detailsVC.detailsModel = _foodArray[_selectedIndexPath.section].spus[_selectedIndexPath.row];
//    
//    [pageVC setViewControllers:@[detailsVC] direction: UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    [pageVC setViewControllers:@[[self creatDetailsVC:_selectedIndexPath]] direction:UIPageViewControllerNavigationDirectionForward animated:NO completion:nil];
    
    pageVC.dataSource = self;
    pageVC.delegate = self;
//
    [self cz_addChildController:pageVC intoView:self.view];
    
    //将购物车添加到分也控制器中
    GDBuyCarLL *buyCar = [[GDBuyCarLL alloc]init];
    
    //
    buyCar.buyList = _selectedArray;
    self.buyCarLL = buyCar;
    [self.view addSubview:buyCar];
    
    [buyCar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_equalTo(46);
    }];
    
    //开始接收通知
    NSNotificationCenter *notication = [NSNotificationCenter defaultCenter];
    
    [notication addObserver:self selector:@selector(pageBuyCarAnimated:) name:@"kNoticatioPageVBuyCar" object:nil];
    
}

- (UIViewController *)creatDetailsVC:(NSIndexPath *)currentIndexPath{

    GDDetailsViewController *detailsVC = [[GDDetailsViewController alloc]init];
    
    detailsVC.detailsModel = _foodArray[_selectedIndexPath.section].spus[_selectedIndexPath.row];
    
    detailsVC.currentIndexPath = currentIndexPath;
    
    return detailsVC;
    
}

//细节处理
- (void)pageViewController:(UIPageViewController *)pageViewController didFinishAnimating:(BOOL)finished previousViewControllers:(NSArray<UIViewController *> *)previousViewControllers transitionCompleted:(BOOL)completed{
    _isEND = YES;
}
- (void)pageViewController:(UIPageViewController *)pageViewController willTransitionToViewControllers:(NSArray<UIViewController *> *)pendingViewControllers{
    _isEND = NO;
}

//开始实现上下翻动的局面，向上翻页和向下翻页，两个一起写才会触发事件
//向下翻页
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerAfterViewController:(GDDetailsViewController *)viewController{
    
    // 拿到当前的角标
    NSInteger row = viewController.currentIndexPath.row;
    NSInteger section = viewController.currentIndexPath.section;
    
    row++;
    //判断当前组是否已经走完了
    if(row == _foodArray[section].spus.count){
    
        section ++;
        if(section == _foodArray.count){
            return nil;
        }
        row = 0;
    }
    
    //获得新的indexPath
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
    //显示新的页面
    return  [self creatDetailsVC:newIndexPath];
    
}

//向上翻页
- (UIViewController *)pageViewController:(UIPageViewController *)pageViewController viewControllerBeforeViewController:(GDDetailsViewController *)viewController{
    
    NSInteger row = viewController.currentIndexPath.row;
    NSInteger section = viewController.currentIndexPath.section;
    
    row--;
    //到头了
    if(row < 0){
        section --;
        if(section < 0){
            return nil;
        }
        row = _foodArray[section].spus.count - 1;
    }
    
    NSIndexPath *newIndexPath = [NSIndexPath indexPathForRow:row inSection:section];
    
    return  [self creatDetailsVC:newIndexPath];
    
}
- (void)pageBuyCarAnimated:(NSNotification *)infor{

    //使用的是同一个数组，同一个购物车，但是动画得重新设置一边
    
    //先获得数据
    NSDictionary *dic = infor.userInfo;
    
    //拿到起点
    CGPoint startP = [dic[@"startP"]CGPointValue];
    
    //获得数据
    GDDetailsFoodModel *selectedMoel = dic[@"model"];
    
    //数据统一的加减，全部都在控制器中进行添加
//    selectedMoel.buyCount ++;
    
    //开始添加动画，集成一个动画的方法
    [self addAnimatedWithPoint:startP];
    
    if(![_selectedArray containsObject:selectedMoel]){
    
        [_selectedArray addObject:selectedMoel];
    }
    
}

- (void)addAnimatedWithPoint:(CGPoint)startP{

    UIImageView *redImagView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"icon_food_count_bg"]];
    redImagView.center = startP;

    //将小红点添加到keyWindow中
    [[UIApplication sharedApplication].keyWindow addSubview:redImagView];
    //创建关键帧动画
    CAKeyframeAnimation *keyAni = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    
    //创建路径 贝赛尔曲线
    UIBezierPath *path = [UIBezierPath bezierPath];
    //起点
    [path moveToPoint:startP];
    
    //控制点
    CGPoint controlP = CGPointMake(startP.x - 50, startP.y - 100);
    
    //终点
    CGPoint endP = CGPointMake(50, [UIScreen mainScreen].bounds.size
                               .height - 46);
    
    //将控制点 终点 添加到路径上
    [path addQuadCurveToPoint:endP controlPoint:controlP];
    
    keyAni.path = path.CGPath;
    keyAni.duration = 1;
    keyAni.delegate = self;
    
    //将红点进行存储
    [keyAni setValue:redImagView forKey:@"red"];
    
    //将小红点的layer添加动画
    [redImagView.layer addAnimation:keyAni forKey:@"keyAni"];
    
    
}
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    
    //将小红点取出删掉
    UIImageView *redImage = (UIImageView *)[anim valueForKey:@"red"];
    
    [redImage removeFromSuperview];
    
    _buyCarLL.buyList = _selectedArray;
}

//销毁通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
